//
//  SEGHLBPublishViewModel.m
//  SEGViewModel
//
//  Created by 梁学彰 on 2020/11/16.
//

#import "SEGHLBPublishViewModel.h"
#import "SEGCommunitySocialManager.h"

@implementation SEGHLBPublishViewModel
#pragma mark - life cycle

#pragma mark - init
- (void)initDataWithDisplayType:(SEGHLBPublishVCDisplayStyle)disPlayType {
    switch (disPlayType) {
        case SEGHLBPublishVCHelpDisplayStyle:
            self.cellKeyArray = @[kSEGHLBPublishContentTableViewCell, kSEGHLBPublishImageTableViewCell, kSEGHLBPublishLocationTableViewCell];
            self.classifyType = SEGEnumIdelExchange_Help;
            self.photoMaxCount = 9;
            break;
        case SEGHLBPublishVCShareDisplayStyle:
            self.classifyType = SEGEnumIdelExchange_Chat;
            self.cellKeyArray = @[kSEGHLBPublishContentTableViewCell, kSEGHLBPublishImageTableViewCell, kSEGHLBPublishLocationTableViewCell];
            self.photoMaxCount = 9;
            break;
        case SEGHLBPublishVCMarketDisplayStyle:
            self.cellKeyArray = @[kSEGHLBPublishTitleTableViewCell, kSEGHLBPublishContentTableViewCell, kSEGHLBPublishImageTableViewCell, kSEGHLBPublishMarketTableViewCell];
            self.classifyType = SEGEnumIdelExchange_SecondHand;
            self.photoMaxCount = 6;
            break;
        default:
            break;
    }
}

#pragma mark - send request
- (RACSignal *)sendUpLoadImageRequest {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        self.hasSubmit = YES;
        [subscriber sendNext:@"1"];
        //只上传没有url的图片，也就是新增图片
        NSArray *uploadArr = [self.savePicArray subarrayWithRange:NSMakeRange(self.saveUrlArray.count, self.savePicArray.count - self.saveUrlArray.count)];
        if(uploadArr.count > 0) {
            [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:uploadArr progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if(isSuccessed) {
                    NSArray *data = result[@"data"];
                    //存储图片链接
                    [self.saveUrlArray addObjectsFromArray:data];
                    [subscriber sendCompleted];
                }else {
                    self.hasSubmit = NO;
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
        } else {
            [subscriber sendCompleted];
        }
        return nil;
    }];
    return signal;
}

/// 请求发布求助&邻里分享
- (RACSignal *)seg_requestPublishNeigbourhoodDataWithDisplayType:(SEGHLBPublishVCDisplayStyle)displayType contentText:(NSString *)text {
    
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"objId"] = @"";
        params[@"objType"] = @"2";
        params[@"quizContent"] = @"";
        params[@"userId"] = kAccountUserID;
        params[@"quizTypeId"] = @"";
        params[@"quizRangeId"] = @"3";
        params[@"regionId"] = [SEGProfileManager sharedManager].profile.cityId;
        params[@"organId"] = kAccountCommunityID;
        params[@"linkUrl"] = @"";
        params[@"linkTitle"] = @"";
        params[@"communityName"] = [NSString stringWithFormat:@"来自%@ %@", kAccountCityName, kAccountCommunityName];
        params[@"communityId"] = kAccountCommunityID;
        params[@"creator"] = kAccountNickName;
        params[@"quizContent"] = text;
        NSString* urlString = [self.saveUrlArray componentsJoinedByString:@","];
        params[@"quizPic"] = urlString ?: @"";
        
        if (displayType == SEGHLBPublishVCHelpDisplayStyle) {
            params[@"quizTypeId"] = @"10002";
            params[@"isBroadCast"] = @"1";
        } else {
            params[@"quizTypeId"] = @"14"; //线上其他类型的id
        }
        
        SEGCommunitySocialManager *manager = [[SEGCommunitySocialManager alloc] init];
        [manager requestSaveQuizWithParams:params Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@"0"];
            if (isSuccessed) {
                //帮帮发帖积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.postForHelp finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                // 刷新邻里圈
                [[NSNotificationCenter defaultCenter] postNotificationName:SEGPublishGoodsFinishedNotification object:nil];

                [subscriber sendCompleted];
            }else {
                self.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                
            }
        }];
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)requestSubmitGoodsIdelWithDict:(NSDictionary *)dict titleTextFieldText:(NSString *)titleTextFieldText contentTextViewText:(NSString *)contentText publishStatus:(SEGPublishStatus)publishStatus
{
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        NSMutableDictionary *parms = [NSMutableDictionary dictionaryWithDictionary:dict];
        [parms setValuesForKeysWithDictionary:@{
                                                @"goodsId" : self.goodsId, // 0表示新增，大于0表示修改
                                                @"title" : titleTextFieldText, //商品标题
                                                @"type" : [NSString stringWithFormat:@"%lu",(unsigned long)self.classifyType], // 发布类型
                                                @"classId" : self.classId, // 商品分类
                                                @"exp" : contentText, // 商品描述
                                                @"img" : [self.saveUrlArray componentsJoinedByString:@","] // 商品图片，多个用','分格
                                                }];
        if (publishStatus == SEGPublishStatus_Republished) {
            [parms setObject:@"1" forKey:@"status"];
        }
        
        //请求提交接口
        WeakSelf;
        [self.sHManager requestSubmitGoodsIdelWithParams:parms finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@"0"];
            if (isSuccessed) {
                weakSelf.hasSubmit = YES;
                //闲置发帖积分行为设置
                [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.idle module:SEGIntegralModule.neighborhoodCircle businessID:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                }];
                [subscriber sendCompleted];
                
            } else {
                weakSelf.hasSubmit = NO;
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
            }
        }];
        
        
        return nil;
    }];
    return signal;
}


- (RACSignal *)publishNeihborhoodShareDataWithDisplayType:(SEGHLBPublishVCDisplayStyle)displayType contentText:(NSString *)text {
    return [RACSignal concat:@[[self sendUpLoadImageRequest],[self seg_requestPublishNeigbourhoodDataWithDisplayType:displayType contentText:text]]];
}

- (RACSignal *)submitGoodsIdelWithDict:(NSDictionary *)dic title:(nonnull NSString *)title titleTextFieldText:(nonnull NSString *)titleTextFieldText contentTextViewText:(nonnull NSString *)contentText publishStatus:(SEGPublishStatus)publishStatus{
    return [RACSignal concat:@[[self sendUpLoadImageRequest],[self requestSubmitGoodsIdelWithDict:dic titleTextFieldText:titleTextFieldText contentTextViewText:contentText publishStatus:publishStatus]]];
}
#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods

#pragma mark - setter and getter
#pragma mark - Getter & Setter
- (NSMutableArray *)savePicArray {
    if (!_savePicArray) {
        _savePicArray = [NSMutableArray array];
    }
    return _savePicArray;
}

- (NSMutableArray *)saveUrlArray {
    if (!_saveUrlArray) {
        _saveUrlArray = [NSMutableArray array];
    }
    return _saveUrlArray;
}

- (SEGSHManager*)sHManager {
    if (!_sHManager) {
        _sHManager = [[SEGSHManager alloc] init];
    }
    return _sHManager;
}







@end
